from django.shortcuts import render

# Create your views here.
import random

from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse, JsonResponse
from iHome.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
import json
import logging

logger = logging.getLogger('django')
from celery_tasks.sms.tasks import send_sms_verify_code
from iHome.libs.yuntongxun.ccp_sms import CCP


# 图片
class ImageCodeView(View):
    def get(self, request):
        # 提取参数
        cur = request.GET.get('cur')
        # 调用captcha模块生成验证码和图片
        text, image = captcha.generate_captcha()
        # 连接verify_code库
        conn = get_redis_connection('verify_code')
        conn.setex('img_%s' % cur, 300, text)
        return HttpResponse(image, content_type='image/jpg')


# 短信
class SMSCodeView(View):
    def post(self, request):
        # 提取参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        id = data.get('id')
        text = data.get('text')
        # 在一开始,先对提取标志数据,判断相同的电话操作是否超过60秒了, 避免短信频繁操作
        # 3.创建链接到redis的对象
        conn = get_redis_connection('verify_code')
        send_flag = conn.get('send_flag_%s' % mobile)
        if send_flag:
            logger.warning('短信发送过于频繁')
            return JsonResponse({'errno': 4201, 'errmsg': '短信发送过于频繁'})
        # 2.整体校验参数
        if not all([mobile, id, text]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': '缺少参数'
            })
        # 4.提取图形验证码
        image = conn.get('img_%s' % id)
        if image is None:
            return JsonResponse({'errno': 4004, 'errmsg': '图形验证码失效'})
        # 5.删除redis的图形验证码,避免恶意测试图形验证码
        try:
            conn.delete('img_%s' % id)
        except Exception as e:
            print(e)
            logger.error(e)
        # 6.对比图形验证码
        image = image.decode()
        if text.lower() != image.lower():
            return JsonResponse({
                'errno': 4004,
                'errmsg': '图形验证码错误'
            })
        # 7.生成短信验证码:生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        # # 保存短信验证码
        # conn.setex('img_%s'%mobile,300,sms_code)
        # # 发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # 通过管道方式优化客户端与redis通讯次数
        # 创建管道
        pl = conn.pipeline()
        # 将redis请求添加到队列
        # 8.保存短信验证码
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # 同时保存一个标记60秒, 用于避免短信轰炸
        pl.setex('send_flag_%s' % mobile, 60, 1)
        # 执行请求
        pl.execute()

        # 9.发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        send_sms_verify_code.delay(mobile, sms_code)
        return JsonResponse({
            'errno': '0',
            'errmsg': '发送成功'
        })
